package com.liuqi.loggers.core.converters;

import com.liuqi.loggers.core.Converter;
import com.liuqi.loggers.core.LoggerEvent;
import java.util.regex.Matcher;

/**
 * format message
 *
 * @author liuqi
 * @date 2024/11/5 16:54
 **/
public class MessageConverter implements Converter {

    @Override
    public String convert(LoggerEvent event) {
        // replace {}
        return format(event.getMessage(), event.getArguments());
    }

    @Override
    public String convert0(LoggerEvent event) {
        return format(event.getMessage(), event.getArguments());
    }

    @Override
    public String name() {
        return "message";
    }

    private String format(String message, Object... parameters) {
        if (message == null) {
            return "null";
        }
        if (parameters == null) {
            return message;
        }
        int startSize = 0;
        int parametersIndex = 0;
        int index;
        String tmpMessage = message;
        while ((index = message.indexOf("{}", startSize)) != -1) {
            if (parametersIndex >= parameters.length) {
                break;
            }
            tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
            startSize = index + 2;
        }
        return tmpMessage;
    }

}
